package middleware

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"mall-portalv2/global"
	"mall-portalv2/internal/model"
	"mall-portalv2/internal/service"
	"mall-portalv2/library/common"
)

func Logs(svc *service.Service) gin.HandlerFunc {
	return func(c *gin.Context) {

		uri := c.Request.RequestURI
		method := c.Request.Method

		userid, _ := c.Get("userid")
		useridStr := fmt.Sprintf("%s", userid)

		global.Log.Info("svc", zap.Any("useridStr", common.Str2Uint(useridStr)))

		insertResult, err := svc.InsertLogs(context.Background(), model.Logs{
			Method: method,
			Uid:    common.Str2Uint(useridStr),
			Uri:    uri,
			IP:     c.ClientIP(),
			//Data:   c.Request.Body,
		})
		if err != nil {
			global.Log.Error("log写入错误", zap.Error(err))
			c.Abort()
		}

		global.Log.Info("logs record success", zap.Any("model id ", insertResult.ID))

		// 处理请求
		c.Next()
	}
}
